<template>
  <div class="register-box">
    <div class="register-activity" v-show="!showQrcode">
      <div class="app-name">{{agentInfo.appName}}</div>
      <div class="agent-box" v-if="agentInfo.name">
        <img :src="agentInfo.logo" alt />
        <span>{{agentInfo.name}}</span>
        邀请您加入{{agentInfo.appName}}
      </div>
      <div class="agent-box" v-else>邀请您加入{{agentInfo.appName}}</div>
      <div class="form-cnt">
        <div class="phone">
          <span class="phone-code" @click="seclectCode">
            {{phoneCode}}
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#icon-xialajiantou" />
            </svg>
          </span>
          <input
            type="tel"
            placeholder="请输入手机号码"
            oninput="value=value.replace(/[^0-9]/g,'')"
            maxlength="11"
            v-model.trim="mobile"
            @blur="blur"
          />
        </div>
        <div class="code">
          <div class="code-box">
            <input
              type="tel"
              placeholder="请输入验证码"
              oninput="value=value.replace(/[^0-9]/g,'')"
              maxlength="6"
              v-model.trim="verificationCode"
              @blur="blur"
            />
          </div>

          <div
            class="send-code"
            :class="{'disabled': disabledBtn}"
            @click="sendCode"
          >{{sendCodeText}}</div>
        </div>
      </div>
      <div class="btn" :class="{'registDisabled': !registDisabled}" @click="nextHandler">注册</div>
    </div>
    <div class="register-qrcode" v-show="showQrcode">
      <div class="top">
        <div class="title">{{agentInfo.appName}}</div>
        <div class="sub">
          全景看房 - AI拓客 - 裂变传播 - 监控意向
          <br />连接客户更简单
        </div>
      </div>
      <div class="qrcode-box">
        <img class="qrcode" :src="qrcodeImg" alt />
        <p>长按识别二维码，关注公众号</p>
      </div>
    </div>
    <van-actionsheet
      v-model="phoneShow"
      :actions="actions"
      cancel-text="取消"
      @select="onSelect"
      @cancel="onCancel"
    />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { checkStrLength, checkStrType } from '@/utils/tool'
import RegisterService from 'SERVICE/registService'
export default {
  data() {
    return {
      uuid: '',
      enterpriseId: '',
      parentUserId: '',
      agentInfo: {},
      mobile: '',
      verificationCode: '',
      actions: [{ name: '中国大陆 +86', phoneCode: '+86' }, { name: '香港 +852', phoneCode: '+852' }],
      phoneCode: '+86',
      phoneShow: false,
      sendCodeText: '获取验证码',
      disabledBtn: true,
      codeTime: 60,
      registStatus: false,
      showQrcode: false,
      qrcodeImg: ''
    }
  },
  created() {
    this.onOff = false
    this.uuid = this.$route.query.uuid || localStorage.getItem('uuid') || ''
    this.enterpriseId = this.$route.query.enterpriseId || localStorage.getItem('enterpriseId') || ''
    this.parentUserId = this.$route.query.parentUserId || localStorage.getItem('parentUserId') || ''
    if (this.parentUserId) {
      this.queryRegisterRecommendInfo()
    }
  },
  // mounted() {
  //   if (localStorage.getItem('backPath')) {
  //     window.addEventListener('popstate', this.goBack, false)
  //   }
  // },
  computed: {
    ...mapGetters(['userInfo']),
    registDisabled() {
      return this.checkPhone() && this.verificationCode.length
    }
  },
  // destroyed() {
  //   if (localStorage.getItem('backPath')) {
  //     window.removeEventListener('popstate', this.goBack, false)
  //   }
  // },
  beforeRouteLeave (to, from, next) {
     let path = localStorage.getItem('backPath')
     console.log(path, !this.onOff)
     if (path && !this.onOff) {
      console.log(path)
      localStorage.removeItem('backPath')
      location.href = path
     } else {
      next()
     }
  },
  watch: {
    mobile() {
      if (this.checkPhone()) {
        this.disabledBtn = false
        // 检测老用户
        this.checkUser()
      } else {
        this.disabledBtn = true
      }
    }
  },
  methods: {
    goBack() {
      let path = localStorage.getItem('backPath')
      location.href = path
    },
    // 获取邀请人信息
    queryRegisterRecommendInfo() {
      RegisterService.queryRegisterRecommendInfo(this.enterpriseId, '', this.parentUserId, this.uuid)
        .then(res => {
          this.agentInfo = res
        })
        .catch()
    },
    // 检测电话号码
    checkPhone() {
      let reg = /^1[3-9]\d{9}$/g
      let checkMobile = (this.phoneCode == '+86' && reg.test(this.mobile)) || (this.phoneCode == '+852' && this.mobile.length === 8)
      return checkMobile
    },
    // 显示区号选择弹框
    seclectCode() {
      this.phoneShow = true
    },
    // 选择区号
    onSelect(item) {
      this.phoneCode = item.phoneCode
      this.phoneShow = false
      this.disabledBtn = !this.checkPhone()
    },
    // 取消选择区号
    onCancel() {
      this.phoneShow = false
    },
    // 发送验证码
    sendCode() {
      if (!this.disabledBtn) {
        this.disabledBtn = true
        const result = RegisterService.sendMsgRegister({ mobile: this.mobile, areaCode: this.phoneCode, enterpriseId: this.enterpriseId })
        this.countDown()
      } else {
        if (this.sendCodeText.includes('重新发送')) {
          this.$toast('验证码发送过于频繁')
        } else {
          this.$toast('手机号码不正确，请检查')
        }
      }
    },
    // 验证码倒计时
    countDown() {
      this.sendCodeText = '重新发送(' + this.codeTime + 's)'
      let timer = setInterval(() => {
        this.codeTime--
        this.sendCodeText = '重新发送(' + this.codeTime + 's)'
        if (this.codeTime < 0) {
          clearInterval(timer)
          this.sendCodeText = '获取验证码'
          this.codeTime = 60
          this.disabledBtn = false
        }
      }, 1000)
    },
    // 检测老用户
    checkUser() {
      RegisterService.checkMobile({
        uuid: this.uuid,
        mobile: this.mobile,
        areaCode: this.phoneCode,
        enterpriseId: this.enterpriseId
      })
        .then(res => {
          if (res.isOldUser) {
            this.$dialog
              .alert({
                title: '提示',
                message: '您已经是老用户了，请进入公众号使用！',
                confirmButtonText: '进入公众号'
              })
              .then(() => {
                this.getOfficialAccountQrCode()
              })
          }
        })
        .catch()
    },
    // 键盘遮挡
    blur() {
      setTimeout(() => {
        document.activeElement.scrollIntoViewIfNeeded(true)
        window.scroll(0, 0)
      }, 100)
    },
    // 检测表单
    nextHandler() {
      // 防止重复提交
      if (this.registStatus) {
        return false
      }
      // 检测字段
      if (this.mobile.length == 0) {
        return this.$toast('请输入手机号码')
      }
      if (!this.checkPhone()) {
        return this.$toast('手机号不正确，请重新输入')
      }
      if (this.verificationCode.length == 0) {
        return this.$toast('请输入验证码')
      }
      this.registStatus = true
      this.register()
    },
    // 注册
    async register() {
      this.onOff = true
      let code = sessionStorage.getItem('wxcode') || ''
      let param = {
        verificationCode: this.verificationCode,
        mobile: this.mobile,
        areaCode: this.phoneCode,
        code: sessionStorage.getItem('officialAccountOpenId') ? '' : code,
        uuid: this.uuid,
        enterpriseId: this.enterpriseId,
        parentUserId: this.parentUserId
      }
      // 公众号获取用户信息
      RegisterService.getUserInfoByCode(param)
        .then(async res => {
          if (res) {
            let user = res.userInfo
            user.cropId = localStorage.getItem('cropId')
            user.userLoginType = res.userLoginType
            user.articleShareFlag = res.articleShareFlag || '0'
            user.token = res.token
            user.jumpToDynamicDetail = res.jumpToDynamicDetail
            user.selfSupport = res.selfSupport
            user.articleAppId = res.articleAppId
            user.appName = res.appName
            user.appLogo = res.appLogo
            user.belong = res.belong
            user.belongType = res.belongType
            user.uuid = res.uuid
            await this.$store.dispatch('getUserInfo', user)
            this.getOfficialAccountQrCode()
          } else {
            this.$toast(res.msg)
            this.registStatus = false
          }
        })
        .catch(err => {
          this.registStatus = false
        })
    },
    // 获取微信公众号二维码
    getOfficialAccountQrCode() {
      RegisterService.getOfficialAccountQrCode({ uuid: this.uuid, enterpriseId: this.enterpriseId })
        .then(res => {
          this.qrcodeImg = res.qrCode
          this.showQrcode = true
        })
        .catch()
    }
  }
}
</script>

<style lang="less" scoped>
.register-box {
  background: #009ee6;
  .register-activity {
    background: #009ee6 url('../../../assets/img/wx/invite2.png') no-repeat left top;
    background-size: 100% auto;
    padding-bottom: 80px;
    position: relative;
    .app-name {
      position: absolute;
      top: 52px;
      left: 24px;
      font-size: 40px;
      color: #fff;
    }
    .agent-box {
      display: flex;
      align-items: center;
      color: #666;
      font-size: 16px;
      color: #fff;
      margin: 0 0 0 24px;
      padding-top: 390px;
      img {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        margin-right: 8px;
      }
      span {
        font-weight: 600;
        margin-right: 5px;
      }
    }
    .form-cnt {
      .phone,
      .code {
        height: 48px;
        margin: 20px 24px 0;
        font-size: 16px;
        color: #445166;
        display: flex;
        align-items: center;
        background-color: #fff;
        border-radius: 4px;
        input {
          flex: 1;
          border: none;
          padding: 0 5px 0 10px;
          &::placeholder {
            padding-top: 0.12rem;
          }
        }
      }
      .code-box {
        flex: 1;
        height: 36px;
        display: flex;
        align-items: center;
        max-width: 180px;
        overflow: hidden;
        input {
          max-width: 100%;
          border: none;
        }
      }
      .send-code {
        width: 120px;
        flex-basis: 120px;
        color: #405170;
        height: 36px;
        margin-left: 10px;
        text-align: center;
        line-height: 36px;
        font-size: 14px;
        &.disabled {
          opacity: 0.5;
        }
      }
      .phone {
        display: flex;
        align-items: center;
        color: rgba(51, 51, 51, 1);
        font-size: 16px;
        padding-left: 5px;
        .phone-code {
          display: flex;
          align-items: center;
          color: rgba(51, 51, 51, 1);
          font-size: 16px;
          padding-left: 5px;
        }
        .icon {
          width: 12px;
          height: 12px;
          margin-left: 5px;
        }
      }
    }
    .btn {
      margin: 0 24px;
      height: 48px;
      border-radius: 4px;
      border: 0;
      color: #405170;
      font-size: 16px;
      line-height: 48px;
      text-align: center;
      margin-top: 30px;
      background-color: #fff;
      font-weight: bold;
      &.registDisabled {
        opacity: 0.5;
      }
    }
  }
  .register-qrcode {
    background: #009ee6 url('../../../assets/img/wx/invitation2.png') no-repeat left top;
    height: 100%;
    background-size: 100% auto;
    font-size: 14px;
    color: #40516f;
    text-align: center;
    padding: 50px 20px;
    box-sizing: content-box;
    .top {
      text-align: left;
      color: #fff;
      .title {
        font-size: 40px;
        font-weight: 600;
        line-height: 56px;
      }
      .sub {
        line-height: 22px;
        font-size: 16px;
      }
    }
    .qrcode-box {
      background-color: #fff;
      border-radius: 12px;
      padding: 40px 0;
      margin-top: 80px;
      img {
        width: 258px;
        height: 258px;
      }
    }
  }
}
</style>